Ext.namespace('AIR2.Format');
/**
 * AIR2.Format
 * Location for Ext.XTemplate formatting functions
 */

/* helper function to optionally create links */
AIR2.Format.createLink = function(text, href, isLinkCls, absLink) {
    if (isLinkCls) {
        var cls = (Ext.isString(isLinkCls)) ? ' class="'+isLinkCls+'"' : '';
        var linkTo = absLink ? href : AIR2.HOMEURL+href;
        return '<a href="'+linkTo+'"'+cls+'>'+text+'</a>';
    } else {
        return text;
    }
}


/* Panel-wise dates in AIR2 will display as short dates */
AIR2.Format.date = function(dtimStr) {
    if (!dtimStr) return '';
    var dt = Date.parseDate(dtimStr, "Y-m-d H:i:s");
    if (dt) dtimStr = dt;
    return dtimStr.format("Y-m-d");
}

/* Some search result dates come as 8-character strings. */
AIR2.Format.dateYmd = function(dtimStr) {
    if (!dtimStr) return '';
    var dt = Date.parseDate(dtimStr, "Ymd");
    if (dt) dtimStr = dt;
    return dtimStr.format("Y-m-d");
}

/* Overlay dates will have the full format YYYY-MM-DD HH:MM:SS am/pm */
AIR2.Format.dateLong = function(dtimStr) {
    if (!dtimStr) return '';
    var dt = Date.parseDate(dtimStr, "Y-m-d H:i:s");
    if (dt) dtimStr = dt;
    return dtimStr.format('Y-m-d g:i:s A');
}
/* In some very specific cases, we need to show "minutes ago" */
AIR2.Format.datePost = function(dtimStr) {
    if (!dtimStr) return '';
    var now = new Date();

    // add a "buffer" minute, for client/server clock differences
    if (dtimStr < now.add(Date.MINUTE, +1)) {
        if (dtimStr > now.add(Date.MINUTE, -1)) {
            // within the last minute
            return '0 minutes ago';
        }
        else if (dtimStr > now.add(Date.HOUR, -1)) {
            // within the last hour
            var elapsed = Math.ceil(dtimStr.getElapsed(now) / 1000 / 60);
            return elapsed + ' minutes ago';
        }
        else if (dtimStr.format('Ymd') === now.format('Ymd')) {
            // on the same calendar day
            var elapsed = Math.ceil(dtimStr.getElapsed(now) / 1000 / 60 / 60);
            return elapsed + ' hours ago';
        }
    }
    return AIR2.Format.dateLong(dtimStr);
}

/* format a source name, optionally returning the link */
AIR2.Format.sourceName = function(sourceObj, returnLink) {
    if (!sourceObj) return "unknown source";

    var name = sourceObj.src_username;
    if (sourceObj.src_first_name && sourceObj.src_last_name)
        name =  sourceObj.src_last_name + ", " + sourceObj.src_first_name;

    return AIR2.Format.createLink(name, '/source/'+sourceObj.src_uuid, returnLink);
}

/* First name, middle initial, last name. Don't use username on blank. */
AIR2.Format.sourceFullName = function(sourceObj, returnLink) {
    if (!sourceObj) return "unknown source";
    
    var name = (sourceObj.src_first_name ? sourceObj.src_first_name : '') +
               (sourceObj.src_middle_initial ? sourceObj.src_middle_initial + '.' : ' ') +
               (sourceObj.src_first_name ? sourceObj.src_last_name : '');
    
    return AIR2.Format.createLink(name, '/source/'+sourceObj.src_uuid, returnLink);
}

/* Source contact info */
AIR2.Format.sourceEmail = function(srcEmail, returnLink) {
    if (!srcEmail || !srcEmail.sem_email) return 'unknown email';
    var e = srcEmail.sem_email;
    return AIR2.Format.createLink(e, 'mailto:'+e, returnLink, true);
}
AIR2.Format.sourcePhone = function(srcPhone) {
    if (!srcPhone || !srcPhone.sph_number) return 'unknown phone';
    var num = srcPhone.sph_number;
    if (srcPhone.sph_country) num = srcPhone.sph_country + num;
    if (srcPhone.sph_ext) num += srcPhone.sph_ext;
    return num;
}
AIR2.Format.sourceMailShort = function(srcMail) {
    var mail = '';
    if (srcMail.smadd_city) mail += srcMail.smadd_city;
    if (srcMail.smadd_state) mail += ', ' + srcMail.smadd_state;
    if (srcMail.smadd_zip) mail += ' ' + srcMail.smadd_zip;
    return mail;
}
AIR2.Format.sourceChannel = function(code) {
    var channels = {
        R: 'Referred by another source',
        Q: 'Query',
        I: 'Game/Interactive Experience',
        E: 'Event/In Person Signup',
        O: 'Opt-in (via programming)/Online Signup',
        G: 'Idea Generator',
        U: 'Not Known',
        N: 'Invitation by newsroom',
        S: 'Strategic Outreach activity'
    };
    return (channels[code]) ? channels[code] : 'Not Known';
}


/* format a user name, optionally returning the link */
AIR2.Format.userName = function(userObj, returnLink) {
    if (!userObj) return "unknown user";

    var name = userObj.user_username;
    if (userObj.user_type != 'S') {
        name = userObj.user_last_name + ", " + userObj.user_first_name;
    }

    return AIR2.Format.createLink(name, '/user/'+userObj.user_uuid, returnLink);
}

/* short format of a user's organization, with background color */
AIR2.Format.userOrgShort = function(userOrgObj, returnLink) {
    if (!userOrgObj) return '';
    return AIR2.Format.orgName(userOrgObj.Organization, returnLink);
}

/* long format of a user's organization */
AIR2.Format.userOrgLong = function(userOrgObj) {
    if (!userOrgObj) return '';
    return AIR2.Format.orgNameLong(userOrgObj.Organization, true);
}

/* the title of a user in an organization */
AIR2.Format.userOrgTitle = function(userOrgObj, ellipsis) {
    if (!userOrgObj) return '';
    var s = (userOrgObj.uo_user_title) ? userOrgObj.uo_user_title : '(no position title)';
    if (ellipsis) s = Ext.util.Format.ellipsis(s, ellipsis);
    return s;
}

/* format a user's primary phone number, if it exists */
AIR2.Format.userPhone = function(obj) {
    if (obj.UserPhoneNumber && obj.UserPhoneNumber.length > 0) {
        var p = obj.UserPhoneNumber[0];
        return p.uph_number + (p.uph_ext ? ' ('+p.uph_ext+')' : '');
    }
    else if (obj.uph_number) {
        return obj.uph_number + (obj.uph_ext ? ' ('+obj.uph_ext+')' : '');
    }
    return '(no phone)';
}

/* format a user's primary email, if it exists */
AIR2.Format.userEmail = function(obj, returnLink) {
    if (obj.UserEmailAddress && obj.UserEmailAddress.length > 0) {
        var e = obj.UserEmailAddress[0].uem_address;
        return AIR2.Format.createLink(e, 'mailto:'+e, returnLink, true);
    }
    else if (obj.uem_address) {
        var e = obj.uem_address;
        return AIR2.Format.createLink(e, 'mailto:'+e, returnLink, true);
    }
    return '(no email)';
}

/* format the profile photo of a user */
AIR2.Format.userPhoto = function(obj, width, height, noCache) {
    var src = AIR2.HOMEURL + '/user/' + obj.user_uuid + '/photo';
    if (noCache) src += '?_dc=' + (new Date().getTime());

    var tag = '<img src="' + src + '" alt="user_photo"';
    if (width) tag += ' width=' + width;
    else if (height) tag += ' height=' + height;
    tag += '></img>';

    return tag;
}

/* format the title of an inquiry, optionally returning the link */
AIR2.Format.inquiryTitle = function(inquiryObj, returnLink) {
    var noTags = Ext.util.Format.ellipsis(
        Ext.util.Format.stripTags(inquiryObj.inq_ext_title), 110, true);

    return AIR2.Format.createLink(noTags, '/inquiry/'+inquiryObj.inq_uuid, returnLink);
}

/* format a submission as a "MORE" link */
AIR2.Format.submissionMore = function(submObj) {
    return AIR2.Format.createLink('more&nbsp;»', '/submission/'+submObj.srs_id, true);
}

/* format an organization name, adding color */
AIR2.Format.orgName = function(orgObj, returnLink) {
    if (!orgObj) return 'unknown organization';
    if (returnLink) {
        return '<a class="air2-newsroom" style="background-color:#' +
            orgObj.org_html_color + '" href="' + AIR2.HOMEURL + '/organization/' +
            orgObj.org_uuid + '">' + orgObj.org_name + '</a>';
    }
    else {
        return '<span class="air2-newsroom" style="background-color:#' +
            orgObj.org_html_color + '">' + orgObj.org_name + '</span>';
    }
}

/* format an org name, optionally returning the link */
AIR2.Format.orgNameLong = function(orgObj, returnLink) {
    if (!orgObj) return 'unknown organization';
    return AIR2.Format.createLink(orgObj.org_display_name, '/organization/'+orgObj.org_uuid, returnLink);
}

/* format the organization logo image */
AIR2.Format.orgLogo = function(obj, width, height, noCache) {
    var src = AIR2.HOMEURL + '/organization/' + obj.org_uuid + '/logo';
    if (noCache) src += '?_dc=' + (new Date().getTime());

    var tag = '<img src="' + src + '" alt="org_logo"';
    if (width) tag += ' width=' + width;
    else if (height) tag += ' height=' + height;
    tag += '></img>';
    return tag;
}

AIR2.Format.projectName = function(prjObj, returnLink) {
    if (!prjObj) return 'unknown project';
    return AIR2.Format.createLink(prjObj.prj_display_name, '/project/'+prjObj.prj_uuid, returnLink);
}

/* format a tag, trimming IPTC tags */
AIR2.Format.tagName = function(tagObj) {
    var result = tagObj.tm_name;
    if (tagObj.tm_type == 'I') {
        var split = tagObj.IptcMaster.iptc_name.lastIndexOf('/');
        if (split) result = tagObj.IptcMaster.iptc_name.substr(split+1);
    }
    return Ext.util.Format.trim(result);
}

/* format batch last use */
AIR2.Format.batchLastUse = function(batchObj) {
    if (batchObj.batch_last_use) {
        return AIR2.Format.datePost(batchObj.batch_last_use);
    }
    return 'No uses';
}

/* format batch number of items */
AIR2.Format.batchCount = function(batchObj) {
    var str = (batchObj.batch_count || Ext.isNumber(batchObj.batch_count))
        ? batchObj.batch_count : 'Unknown';
    if (batchObj.batch_type == 'U') str += ' Users';
    if (batchObj.batch_type == 'P') str += ' Projects';
    if (batchObj.batch_type == 'S') str += ' Sources';
    if (batchObj.batch_type == 'O') str += ' Newsrooms';
    if (batchObj.batch_count == 1) str = str.substr(0, str.length-1);
    return str;
}

/* format a boolean in friendly way */
AIR2.Format.bool = function(bool) {
    if (bool) {
        return 'Yes';
    }
    else {
        return 'No';
    }
}

/* format tank info */
AIR2.Format.tankName = function(tankObj, returnLink) {
    var name = tankObj.tank_file_name;
    return AIR2.Format.createLink(name, '/import/'+tankObj.tank_uuid, returnLink);
}
AIR2.Format.tankType = function(tankObj) {
    /* type => [icon, tooltip] */
    var t = {
        F: ['air2-icon-formbuilder', 'Formbuilder'],
        C: ['air2-icon-upload', 'CSV Upload']
    };
    var def = t[tankObj.tank_type];
    return '<span class="air2-icon '+def[0]+'" ext:qtip="'+def[1]+'"></span>';
}
AIR2.Format.tankStatus = function(tankObj, returnText) {
    /* status => [icon, tooltip] */
    var s = {
        N: ['air2-icon-needs-work', 'Waiting for Upload'],
        I: ['air2-icon-working', 'Uploading'],
        S: ['air2-icon-check-grey', 'In Tank'],
        F: ['air2-icon-warning', 'Upload Failed'],
        D: ['air2-icon-working', 'Working'],
        T: ['air2-icon-check', 'Imported'],
        E: ['air2-icon-warning', 'Import Errors']
    };
    var def = s[tankObj.tank_status];
    if (returnText) {
        return def[1];
    }
    else {
        return '<span class="air2-icon '+def[0]+'" ext:qtip="'+def[1]+'"></span>';
    }
}

AIR2.Format.shared = function(isShared) {
    if (isShared) return '<li class="green">Yes</li>';
    else return '<li class="red">No</li>';
}

AIR2.Format.status = function(status) {      
    if (status == 'A') return '<li class="green">Active</li>';
    else return '<li class="red">Inactive</li>';
}      

